<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Sa extends CI_Controller {

    //登陆验证
    public function __construct() {
        parent::__construct();
        $admin = $this->session->userdata('admin');
        if (empty($admin) || $admin != "vnuytxfzjhkhj") {
            redirect("/sm/login", 'location');
        }
    }

    //后台
    public function index() {
        $this->load->view('sa_index');
    }

    //后台左部菜单
    public function left() {
        $this->load->view('sa_left');
    }

    //后台初次界面
    public function main() {
		echo 'Hello World<br/>访问作者博客：<a href="http://blog.clmao.com" target="_blank">常乐猫</a>';
    }

    //添加内容视图
    public function addContent() {
        include './public/fckeditor/fckeditor_php5.php';
        $fck = new FCKeditor('content');
        $fck->Value = "";
        $fck->BasePath = base_url() . "/public/fckeditor/";
        $data['fck'] = $fck->CreateHtml();
        $this->load->helper('form');
        $this->load->model('content_model', 'art');
        $data['c_id'] = $this->art->get_cid();
        $this->load->view('sa_addContent', $data);
    }

    //添加内容的操作
    public function addContentProcess() {
        $this->load->library('form_validation');
        $status = $this->form_validation->run('content');
        if (empty($_FILES)) {
            echo '图片不能为空';
            die;
        }
        if ($status) {
           // echo $_POST['content'];die;
            //文件上传------------------------
            $y = date("m", time());
            if (date("m", time()) >= 7) {
                $y = $y . "2/";
            } else {
                $y = $y . "1/";
            }
            if (!is_dir('./up/' . $y)) {
                mkdir('./up/' . $y);
            }
            if (!is_dir('./bp/' . $y)) {
                mkdir('./bp/' . $y);
            }
            $config['upload_path'] = './up/' . $y;
            $config['allowed_types'] = 'jpg';
            $config['max_size'] = '10000';
            $filename = time() . rand(10, 99);
            $config['file_name'] = $filename;
            $this->load->library('upload', $config);
            //执行上传
           $status = $this->upload->do_upload('viewfile');
            $wrong = $this->upload->display_errors();
            if ($wrong) {
                print_r($wrong);
            }
            $info = $this->upload->data();
            //缩略图
            $this->load->model('content_model', 'art');
            $pContent = mb_convert_encoding($_POST['content'],'UTF-8');
            $data = array(
                'title' => $this->input->post('title'),
                'show_num' => $this->input->post('show_num'),
                'c_id' => $this->input->post('c_id'),
                'thumb' => $y . $info['file_name'],
                'big_img' => $y . $info['file_name'],
                'is_visable' => $this->input->post('is_visable'),
                'content' => $pContent,
                'time' => time()
            );
            // p($data);die;("妳係我的友仔", "UTF-8", 
            $this->art->add($data);
            $this->createXML();
            $this->createHtml();
            include './my/libraries/Resizeimage.php';
            $thumb = new Resizeimage('./up/' . $y . $filename . '.jpg', '210', '160', 'true', './bp/' . $y . $filename . '.jpg');
            redirect('/sa/addContent?flag=s', 'location');
        } else {
            include './public/fckeditor/fckeditor_php5.php';
            $fck = new FCKeditor('content');
            $fck->Value = "";
            $fck->BasePath = base_url() . "/public/fckeditor/";
            $data['fck'] = $fck->CreateHtml();
            $this->load->helper('form');
            $this->load->view('sa_addContent', $data);
        }
    }

    //内容列表
    public function listcontent() {
        $this->load->model('content_model', 'art');
        $number = $this->art->count_content();
        $this->load->library('pagination');
        $config['base_url'] = site_url('sa/listcontent/'); //路径            
        $config['total_rows'] = $number;  //配置记录总条数          
        $config['per_page'] = 10; //配置每页显示的记录数 
        $config['first_tag_open'] = '<div>';
        $config['first_tag_close'] = '</div>';
        $config['uri_segment'] = 3;
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['last_link'] = '末页';
        $config['first_link'] = '首页';
        $config['num_links'] = 4;
        //配置偏移量在url中的位置  
        $config['cur_page'] = $this->uri->segment(3);
        $tab['table'] = $this->art->list_posts($config ['per_page'], $this->uri->segment(3)); //当前页显示的数据 
        $this->pagination->initialize($config);
        $this->load->view('sa_listContent', $tab);   //调页面  传数据
    }

    //删除内容
    public function delcontent() {
        $this->load->model('content_model', 'art');
        $this->art->del_content($_GET['id'] + 0);
        if ($this->db->affected_rows()) {
            redirect("/sa/listcontent?flag=s", 'location');
        }
    }

    //编辑内容的视图
    public function edithContent() {
        $this->load->model('content_model', 'art');
        $data['c_id'] = $this->art->get_cid();
        $content = $this->art->get_content($_GET['id'] + 0);
        $this->load->helper('form');
        include './public/fckeditor/fckeditor_php5.php';
        $fck = new FCKeditor('content');
        $fck->Value = $content[0]['content'];
        $fck->BasePath = base_url() . "/public/fckeditor/";
        $data['fck'] = $fck->CreateHtml();
        $this->load->view('sa_editContent', $data);
    }

    //编辑内容的处理
    public function edithContentProcess() {


        $this->load->model('content_model', 'art');
        $id = $this->input->post('id');
        $cid = $this->input->post('c_id');
        $title = $this->input->post('title');
        $show = $this->input->post('show_num');
        $isv = $this->input->post('is_visable');
        $pcontent = mb_convert_encoding($_POST['content'],'UTF-8');
        $data = array(
            'title' => $title,
            'show_num' => $show,
            'c_id' => $cid,
            'is_visable' => $isv,
            'content' => $pcontent
        );
        $this->art->update_content($id, $data);echo $this->db->last_query();
die;
        if ($this->db->affected_rows()) {
            echo '修改成功';
            redirect("/sa/edithContent?flag=s&id=$id&title=$title&c_id=$cid&is_visable=$isv&show_num=$show", 'location');
            exit();
        }
    }

    //添加分类的视图
    public function addCategory() {
        $this->load->helper('form');
        $this->load->view('sa_addCategory');
    }

    //添加分类的动作
    public function addCategoryProcess() {
        $this->load->library('form_validation');
        $status = $this->form_validation->run('category');

        if ($status) {
            $data = array(
                'title' => $this->input->post('title')
            );
            $this->load->model('Category_model', 'art');
            $this->art->add($data);
            //echo $this->db->last_query();
            redirect('/sa/addCategory?flag=s', 'location');
        } else {
            $this->load->helper('form');
            $this->load->view('sa_addCategory');
        }
        //  echo $this->db->last_query();
    }

    //分类列表
    public function listCategory() {
        $this->load->model('category_model', 'art');
        $number = $this->art->count_category();
        $this->load->library('pagination');
        $config['base_url'] = site_url('sa/listCategory/'); //路径            
        $config['total_rows'] = $number;  //配置记录总条数          
        $config['per_page'] = 10; //配置每页显示的记录数 
        $config['first_tag_open'] = '<div>';
        $config['first_tag_close'] = '</div>';
        $config['uri_segment'] = 3;
        $config['next_link'] = '下一页';
        $config['prev_link'] = '上一页';
        $config['last_link'] = '末页';
        $config['first_link'] = '首页';
        $config['num_links'] = 4;
        //配置偏移量在url中的位置  
        $config['cur_page'] = $this->uri->segment(3);
        $tab['table'] = $this->art->list_posts($config ['per_page'], $this->uri->segment(3)); //当前页显示的数据 
        $this->pagination->initialize($config);
        $this->load->view('sa_listCategory', $tab);   //调页面  传数据
    }

    /**
     * 编辑分类视图
     */
    public function editCategory() {
        $this->load->helper('form');
        $this->load->view('sa_editCategory');
    }

    /**
     * 编辑分类的处理
     */
    public function edithCategoryProcess() {
        $this->load->library('form_validation');
        $status = $this->form_validation->run('category');
        if ($status) {
            $this->load->model('Category_model', 'art');
            $id = $this->input->post('id');
            $title = $this->input->post('title');
            $this->art->update_category($id, $title);
            //echo $this->db->last_query();
            redirect("/sa/editCategory?flag=s&id=$id&title=$title", 'location');
        } else {
            $this->load->helper('form');
            $this->load->view('sa_editCategory');
        }
    }

    /**
     * 删除分类的处理
     */
    public function delCategory() {
        $this->load->model('Category_model', 'art');
        $this->art->del_category($_GET['id'] + 0);
        if ($this->db->affected_rows()) {
            redirect("/sa/listCategory?flag=s", 'location');
        }
    }

    /*
     * 生成XML
     */

    public function createXML() {
        $this->load->model('content_model', 'art');
        $this->load->model('category_model', 'category');

        function create_item($dom, $item, $data, $attribute) {
            if (is_array($data)) {
                foreach ($data as $key => $val) {
                    //  创建元素 
                    $$key = $dom->createElement($key);
                    $item->appendchild($$key);
                    //  创建元素值 
                    $text = $dom->createTextNode($val);
                    $$key->appendchild($text);
                    if (isset($attribute[$key])) {
                        //  如果此字段存在相关属性需要设置 
                        foreach ($attribute[$key] as $akey => $row) {
                            //  创建属性节点 
                            $$akey = $dom->createAttribute($akey);
                            $$key->appendchild($$akey);
                            // 创建属性值节点 
                            $aval = $dom->createTextNode($row);
                            $$akey->appendChild($aval);
                        }
                    }
                }
            }
        }

        header('Content-type: application/xml');
        $allId = $this->art->all_content_id();
        $cId = $this->category->get_all_category();
        $data_array = array();
        $data_array[0]['loc'] = base_url();
        $data_array[0]['lastmod'] = date('Y-m-d\TH:i:s', time()) . "+00:00";
        $data_array[0]['changefreq'] = 'daily';
        $data_array[0]['priority'] = '1.0';
        foreach ($allId as $k => $v) {
            $data_array[$k + 1]['loc'] = site_url('sm/content/' . $v['id']);
            $data_array[$k + 1]['lastmod'] = date('Y-m-d\TH:i:s', $v['time']) . "+00:00";
            $data_array[$k + 1]['changefreq'] = 'monthly';
            $data_array[$k + 1]['priority'] = '0.6';
        }
        foreach ($cId as $k => $v) {
            $data_array[] = array(
                'loc' => site_url('sm/category/' . $v['id']),
                'lastmod' => date('Y-m-d\TH:i:s', time()) . "+00:00",
                'changefreq' => 'Weekly',
                'priority' => '0.1',
            );
        }
        //  属性数组 

        $attribute_array = array(
        );
        //  创建一个XML文档并设置XML版本和编码。。 
        $dom = new DomDocument('1.0', 'utf-8');
        //  创建根节点 
        $article = $dom->createElement('urlset');
        $article->SetAttribute("xmlns:xsi", 'http://www.w3.org/2001/XMLSchema-instance');
        $article->SetAttribute("xmlns", 'http://www.sitemaps.org/schemas/sitemap/0.9');
        $article->SetAttribute("xsi:schemaLocation", 'http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd');
        $dom->appendchild($article);
        foreach ($data_array as $data) {
            $item = $dom->createElement('url');
            $article->appendchild($item);
            create_item($dom, $item, $data, $attribute_array);
        }
        $dom->save("sitemap_clmao.xml");
    }
    /*
     * 生成站点地图HTML
     */
    public function createHtml(){
        $this->load->model('content_model', 'art');
        $this->load->model('category_model', 'category');
        $allId = $this->art->all_content_id();
        $cId = $this->category->get_all_category();
        $data_array = array();
        //print_r($allId);print_r($cId);
        foreach ($allId as $k => $v) {
            $data_array[0][]='<li><a href="' . site_url('sm/content/' . $v['id']) .'">' . $v['title'] .'</a></li>';
       }
        foreach ($cId as $k => $v) {
            $data_array[1][] =  '<li><a href="' . site_url('sm/category/' . $v['id']) .'">' . $v['title'] .'</a></li>';
        }
        //print_r($data_array);
        define('BLOG.CLMAO.COM','BLOG.CLMAO.COM');
        include('./config.php');
        $str = '<!doctype html><html><head><meta charset="utf-8"><meta name="keywords" content="站点地图," /><meta name="author" content="blog.clmao.com" /><meta name="copyright" content="blog.clmao.com" /><title>站点地图</title><style type="text/css">body {font-family: Verdana;FONT-SIZE: 12px;MARGIN: 0;color: #000000;background: #ffffff;}nav{ width:90%; margin-left:5%;display:block; height:20px; line-height:20px; border:#CCC solid 1px;  padding-left:20px;}section{display:block; margin-top:20px; line-height:20px; border:#CCC solid 1px; width:90%; margin-left:5%; padding-left:20px;}li{ padding:0px; margin:0px; list-style:none; }a{ color:#000; text-decoration:none;}a:hover{ color:#F00;}ul{padding:0px; margin:0px;padding-bottom:5px;}h2{ margin-left:5%;}footer{ width:100%; text-align:center; margin-top:50px;}</style></head><body><h2>';
        $homeUrl = base_url();
        $str = $str.HOMENAME . ' 站点地图</h2><nav><a href="'.$homeUrl.'">'.HOMENAME.'</a>'.' >> <a href="';
        $str = $str .$homeUrl .'sitemap.html">站点地图</a></nav><section><strong>最新文章</strong><ul>';
        foreach ($data_array[0] as  $value) {
            $str.=$value;
        }
        $str.='</ul></section><section><strong>分类目录</strong><ul>';
        foreach ($data_array[1] as  $value) {
            $str.=$value;
        }
        $str.='</ul></section><footer>Powered by <a href="http://blog.clmao.com">Clmao</a></footer></body></html>';
        file_put_contents('sitemap.html',$str);
    }
    /*
     * 链接视图
     */

    public function addLink() {
        $this->load->helper('form');
        $this->load->view('sa_addLink');
    }

    /*
     * 链接处理
     */

    public function addLinkProcess() {
        $this->load->library('form_validation');
        $status = $this->form_validation->run('link');
        if ($status) {
            $data = array(
                'title' => $this->input->post('title'),
                'src' => $this->input->post('src'),
                'flag' => $this->input->post('flag')
            );
            $this->load->model('link_model', 'link');
            $this->link->add($data);
            if ($this->db->affected_rows()) {
                redirect("/sa/addLink?flag2=s&flag=" . $this->input->post('flag'), 'location');
            }
        } else {
            echo '失败，表单信息填写错误';
        }
    }

    /*
     * 链接列表
     */

    public function listLink() {
        $flag = $this->input->get('flag');
        $this->load->model('link_model', 'link');
        $data['res'] = $this->link->get_all_link($flag);
        $data['flag'] = $flag;
        $this->load->view('sa_listLink', $data);
    }

    /*
     * 删除链接
     */

    public function delLink() {
        $this->load->model('link_model', 'link');
        $this->link->del_link($_GET['id'] + 0);
        if ($this->db->affected_rows()) {
            redirect("/sa/listLink?flag2=s&flag=" . $this->input->get('flag'), 'location');
        }
    }

    /*
     * 显示配置文件
     */

    public function editConfig() {
       header("Content-type: text/html; charset=utf-8"); 
       echo '<h3>此处只提供预览功能，请自行修改根目录下的 config.php 文件.</h3>';
       $str = file_get_contents('./config.php');
       highlight_string($str);
        // echo $str;
    }

	/*
	* 退出系统
	*/
	public function exitSys(){
		$this->session->unset_userdata('admin');
		redirect("/sm/login", 'location');
	}

}
